﻿using System;
using System.Collections.Generic;
using System.Linq;
using BlogML.Xml;
using NGM.BlogML.Extensions;
using NGM.BlogML.Models;
using Orchard.Comments.Models;
using Orchard.Comments.Services;
using Orchard.ContentManagement;

namespace NGM.BlogML.Services.Stratagies {
    public class CommentImportStratagy : IImportStratagy {
        private readonly ICommentService _commentService;
        private readonly IDataCleaner _dataCleaner;

        public CommentImportStratagy(ICommentService commentService,
            IDataCleaner dataCleaner) {
            _commentService = commentService;
            _dataCleaner = dataCleaner;
        }

        public bool IsType(object objectToImport) {
            return objectToImport is BlogMLComment;
        }

        public ContentItem Import(ImportSettings importSettings, BlogMLBlog blog, object objectToImport, IContent parentContent) {
            BlogMLComment commentToImport = (BlogMLComment)objectToImport;

            var author = (commentToImport.UserName ?? string.Empty).Truncate(255);
            var dateCreated = commentToImport.DateCreated;

            var existingComment = _commentService.GetCommentsForCommentedContent(parentContent.Id)
                .Where(o => o.Author == author)
                .List()
                .Where(o => o.Record.CommentDateUtc.HasValue && o.Record.CommentDateUtc.Value.Equals(dateCreated))
                .FirstOrDefault();

            if (existingComment != null)
                return existingComment.ContentItem;
            
            var context = new CreateCommentContext {
                Author = author,
                CommentText = (_dataCleaner.Clean(commentToImport.Content.Text, importSettings) ?? string.Empty).Truncate(10000),
                Email = (commentToImport.UserEMail ?? string.Empty).Truncate(255),
                SiteName = (commentToImport.UserUrl ?? string.Empty).Truncate(255),
                CommentedOn = parentContent.Id,
            };

            if (parentContent.As<CommentsPart>().Record.CommentPartRecords == null)
                parentContent.As<CommentsPart>().Record.CommentPartRecords = new List<CommentPartRecord>();

            var comment = _commentService.CreateComment(context, true);
            
            comment.Record.CommentDateUtc = dateCreated;
            comment.Record.UserName = (commentToImport.UserName ?? "Anonymous").Truncate(255);

            if (commentToImport.Approved)
                _commentService.ApproveComment(comment.ContentItem.Id);

            return comment.ContentItem;
        }

        public void ImportAdditionalContentItems<T>(ImportSettings importSettings, BlogMLBlog blog, T objectToImport, IContent parentContent) {
            throw new NotSupportedException();
        }
    }
}